<template>
  <div class="system-config" v-cloak>
    <div class="content_panel_top">
      <h3 class="panel_title">
        <span>{{ $t('operation.appSetting') }}</span>
      </h3>
      <el-form ref="formTop" :model="formTop" :rules="rulesTop" :inline="false" class="module_form">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item prop="appName">
              <el-select v-model="formTop.appName" :placeholder="$t('system.appName')" style="width:100%;" @change="getConfigList">
                <el-option v-for="item in appList" :key="item.id" :value="item.name" :label="`${item.packageName}[${item.name}]`"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="module_content">
      <div class="content_panel project_modules">
        <div class="table_list">
          <table class="gridtable">
            <tr>
              <th>{{ $t('common.configurationItem') }}</th>
              <th>{{ $t('common.setAndOperation') }}</th>
              <th>{{ $t('common.contentOverview') }}</th>
              <th>{{ $t('common.updateTime') }}</th>
            </tr>
            <tr v-if="formKeyShow.content">
              <td>{{ $t('common.lantern') }}</td>
              <td>
                <el-button @click="showSettingsDialog('content', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('content', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.content.viewShow.content | substrText(50)}}</td>
              <td>{{ formOrder.content.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
<!--            <tr>
              <td>{{ $t('common.ABface') }}</td>
              <td>
                <el-switch disabled :active-value="0" :inactive-value="1"></el-switch>
              </td>
              <td>{{ $t('collection.closed') }}</td>
              <td></td>
            </tr>-->
            <tr v-if="formKeyShow.tel">
              <td>{{ $t('common.customerServicePhone') }}</td>
              <td>
                <el-button @click="showSettingsDialog('tel', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('tel', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.tel.value[0].tel}}</td>
              <td>{{ formOrder.tel.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.email">
              <td>{{ $t('common.customerServiceEmail') }}</td>
              <td>
                <el-button @click="showSettingsDialog('email', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('email', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.email.value }}</td>
              <td>{{ formOrder.email.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.privacy_protocol">
              <td>{{ $t('common.privacyAgreement') }}</td>
              <td>
                <el-button @click="showSettingsDialog('privacy_protocol', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('privacy_protocol', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.privacy_protocol.value | substrText(50)}}</td>
              <td>{{ formOrder.privacy_protocol.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.loan_agreement">
              <td>{{ $t('common.loanAgreement') }}</td>
              <td>
                <el-button @click="showSettingsDialog('loan_agreement', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('loan_agreement', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.loan_agreement.value | substrText(50)}}</td>
              <td>{{ formOrder.loan_agreement.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.authorization_content">
              <td>{{ $t('common.authorizationAgreement') }}</td>
              <td>
                <el-button @click="showSettingsDialog('authorization_content', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('authorization_content', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.authorization_content.value | substrText(50)}}</td>
              <td>{{ formOrder.authorization_content.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.about_us">
              <td>{{ $t('common.aboutUs') }}</td>
              <td>
                <el-button @click="showSettingsDialog('about_us', 'edit')" type="text">{{ $t('finance.edit') }}</el-button>
                <el-button @click="showSettingsDialog('about_us', 'check')" type="text">{{ $t('common.check') }}</el-button>
              </td>
              <td>{{ formOrder.about_us.value | substrText(50)}}</td>
              <td>{{ formOrder.about_us.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.can_borrow_new">
              <td>{{ $t('common.newSubCustomerLoan') }}</td>
              <td>
                <el-switch v-model="formOrder.can_borrow_new.status" @change="changeStatus('can_borrow_new')" :active-value="0" :inactive-value="1"></el-switch>
              </td>
              <td>{{ formOrder.can_borrow_new.status === 0 ? $t('collection.activated') : $t('collection.closed') }}</td>
              <td>{{ formOrder.can_borrow_new.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
            <tr v-if="formKeyShow.can_borrow_old">
              <td>{{ $t('common.oldCustomerLoan') }}</td>
              <td>
                <el-switch v-model="formOrder.can_borrow_old.status" @change="changeStatus('can_borrow_old')" :active-value="0" :inactive-value="1"></el-switch>
              </td>
              <td>{{ formOrder.can_borrow_old.status === 0 ? $t('collection.activated') : $t('collection.closed')}}</td>
              <td>{{ formOrder.can_borrow_old.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <!-- 编辑框 -->

    <el-dialog :title="settingsDialog.type ==='edit'? $t('finance.edit'): $t('common.check')" :visible.sync="settingsDialog.settingsDialogShow" :width="dialogWidth">
      <el-form ref="form" :model="form" :rules="rules" :label-width="dialogLableWidth">
        <template v-if="settingsDialog.key ==='content'">
          <div class="likeFormItem">
            <!--状态,用l-form-item其他规则校验会出问题-->
            <label for="">{{$t('common.status') + ':'}}</label>
            <el-switch v-model="form.content.status" :disabled="!isEidt" :active-value="0" :inactive-value="1"></el-switch>
          </div>
          <el-form-item  prop="horse_race_lamp" :label="$t('common.lantern') + ':'">
            <!--走马灯内容：最多不超过500字。-->
            <el-input v-if="isEidt" type="textarea" v-model="form.content.viewShow.content" :placeholder="$t('common.lanternPlaceholder')" :maxlength="500" :rows="6"></el-input>
            <div v-else class="pdr_70">
              <span>{{form.content.viewShow.content}}</span>
            </div>
          </el-form-item>
        </template>
        <el-form-item v-if="settingsDialog.key ==='tel'" prop="tel" :label="$t('common.customerServicePhone') + ':'">
          <!--客服电话-->
          <el-input v-if="isEidt" type="text" v-model="form.tel.value[0].tel" :placeholder="$t('verify.plsInput')"></el-input>
          <span v-else>{{form.tel.value[0].tel}}</span>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key ==='email'" prop="email" :label="$t('common.customerServiceEmail') + ':'">
          <!--客服邮箱-->
          <el-input v-if="isEidt" type="text" v-model="form.email.value" :placeholder="$t('verify.plsInput')"></el-input>
          <span v-else>{{form.email.value}}</span>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key ==='privacy_protocol'">
          <!--隐私协议-->
          <tinymce v-if="settingsDialog.settingsDialogShow" id="d1" :readonly="!isEidt" v-model="form.privacy_protocol.value" :other_options="options"></tinymce>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key ==='loan_agreement'">
          <!--隐私协议-->
          <tinymce v-if="settingsDialog.settingsDialogShow" id="d1" :readonly="!isEidt" v-model="form.loan_agreement.value" :other_options="options"></tinymce>
        </el-form-item>
        <el-form-item v-if="settingsDialog.key ==='authorization_content'">
          <!--隐私协议-->
          <tinymce v-if="settingsDialog.settingsDialogShow" id="d1" :readonly="!isEidt" v-model="form.authorization_content.value" :other_options="options"></tinymce>
        </el-form-item>
        
        <el-form-item v-if="settingsDialog.key ==='about_us'">
          <!--关于我们-->
          <tinymce v-if="settingsDialog.settingsDialogShow" id="d2" :readonly="!isEidt" v-model="form.about_us.value" :other_options="options"></tinymce>
        </el-form-item>
      </el-form>
      <div v-if="isEidt" slot="footer">
        <el-button @click="submitSettngs()" type="primary">{{ $t('common.confirmOk') }}</el-button>
        <el-button @click="settingsDialog.settingsDialogShow = false" type="default">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import tinymce from 'vue-tinymce-editor';

  export default {
    components: {
      tinymce
    },
    data() {
      var horse_race_lampFun = (rule, value, callback) => {
        if (this.form.content.status == 0) {
          if (this.form.content.viewShow.content.trim().length == 0) {
            callback(new Error(this.$tc('verify.tipsLanternEmpty')));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
      var tel = (rule, value, callback) => {
        if (this.form.tel.value[0].tel) {
          callback();
        } else {
          callback(new Error(this.$tc('verify.plsInput')));
        }
      };
      var email = (rule, value, callback) => {
        if (this.form.email.value) {
          const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
          const result = re.test(this.form.email.value);
          if (result) {
            callback();
          } else {
            callback(new Error(this.$tc('common.plsInputTrueEmail')));
          }
        } else {
          callback(new Error(this.$tc('verify.plsInput')));
        }
      };
      return {
        formTop: {
          appName: ''
        },
        rulesTop: {},
        appList: [],
        companyName: this.$storage.get('user').companyName,
        language: this.$storage.getLocal('language'),
        options: {
          height: 400
        },
        formOrder: {
          //跑马灯
          content: {
            status: 1,
            viewShow: {
              content: ''
            }
          },
          //客服电话
          tel: {
            value: [
              {
                tel: '',
                time: ''
              }
            ]
          },
          //客服邮箱
          email: {
            value: ''
          },
          //隐私协议
          privacy_protocol: {
            value: ''
          },
          loan_agreement:{
            value:''
          },
          authorization_content:{
            value:''
          },
          //关于我们
          about_us: {
            value: ''
          },
          //新户/次新户借款
          can_borrow_new: {
            status: 1
          },
          //老户借款
          can_borrow_old: {
            status: 1
          }
        },
        settingsDialog: {
          settingsDialogShow: false,
          type: 'edit',
          key: ''
        },
          formKeyShow: {
              content: false,
              tel: false,
              email: false,
              privacy_protocol: false,
              loan_agreement:false,
              authorization_content:false,
              about_us: false,
              can_borrow_new: false,
              can_borrow_old: false,
          },
        form: {
          //跑马灯
          content: {
            status: 1,
            viewShow: {
              content: ''
            }
          },
          //客服电话
          tel: {
            value: [
              {
                tel: '',
                time: ''
              }
            ]
          },
          //客服邮箱
          email: {
            value: ''
          },
          //隐私协议
          privacy_protocol: {
            value: ''
          },
          loan_agreement:{
            value:''
          },
          authorization_content:{
            value:''
          },
          //关于我们
          about_us: {
            value: ''
          },
          //新户/次新户借款
          can_borrow_new: {
            status: 1
          },
          //老户借款
          can_borrow_old: {
            status: 1
          }
        },
        rules: {
          horse_race_lamp: [
            //跑马灯
            { validator: horse_race_lampFun, trigger: 'blur' }
          ],
          tel: [
            //客服电话
            { validator: tel, trigger: 'blur' }
          ],
          //邮箱
          email: [{ validator: email, trigger: 'blur' }]
        }
      };
    },
    computed: {
      dialogWidth() {
        switch (this.settingsDialog.key) {
          case 'privacy_protocol':
          case 'loan_agreement':
          case 'authorization_content':
          case 'about_us':
            return '1100px';
          default:
            return '500px';
        }
      },
      dialogLableWidth() {
        switch (this.settingsDialog.key) {
          case 'tel':
          case 'email':
            return this.language === 'zh' ? '80px' :'170px';
          case 'privacy_protocol':
          case 'loan_agreement':
          case 'authorization_content':
          case 'about_us':
            return '0';
          default:
            return '80px';
        }
      },
      //弹框是否处于编辑状态
      isEidt() {
        return this.settingsDialog.type === 'edit';
      }
    },
    methods: {
      //订单部分提交
      onSubmitOrder(params) {
        this.$api.systemSetting.batchUpdate(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && '00000000' === error && data) {
            this.$message.success(this.$tc('common.successfulOperation'));
            this.settingsDialog.settingsDialogShow = false;
            this.getConfigList();
          } else {
            this.$message.success(this.$tc('common.failedOperation'));
            this.getConfigList();
          }
        });
      },
      getConfigList() {
        const params = {
          appName: this.formTop.appName
        };
        // 先默认隐藏
        const formKeyShow = this.formKeyShow;
        Object.keys(formKeyShow).forEach(key => {
            formKeyShow[key] = false;
        })
        this.$api.systemSetting.getConfigList(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && '00000000' === error && data.length) {
            for (const key in data) {
              let objTemp = data[key];
              if (typeof this.formOrder[objTemp.key] != 'undefined') {
                this.formOrder[objTemp.key] = objTemp;
                this.formKeyShow[objTemp.key] = true;
              }
            }
            if (this.formKeyShow.tel) {
                this.formOrder.tel.value = JSON.parse(this.formOrder.tel.value);
            }
          }
        });
      },
      showSettingsDialog(key, type) {
        this.settingsDialog.key = key;
        this.settingsDialog.type = type;
        //下面都是解决富文本框赋值的问题
        if (key === 'privacy_protocol' || key === 'about_us'||key==='loan_agreement'||key==='authorization_content') {
          this.form[key] = {};
          setTimeout(() => {
            this.form[key] = JSON.parse(JSON.stringify(this.formOrder[key]));
          }, 0);
        } else {
          this.form[key] = JSON.parse(JSON.stringify(this.formOrder[key]));
        }
        this.settingsDialog.settingsDialogShow = true;
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      },
      changeStatus(key) {
        this.$confirm(
          this.formOrder[key].status === 0
            ? this.$t('common.isOpen')
            : this.$t('common.isClose'),
          this.$t('salesManage.tips'),
          {
            confirmButtonText: this.$t('common.confirmOk'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }
        )
          .then(() => {
            this.submitSettngs(key);
          })
          .catch(() => {
            this.formOrder[key].status = 1 ^ this.formOrder[key].status;
          });
      },
      submitSettngs(key) {
        if (key) {
          // 直接表格内切换状态
          const params = [this.formOrder[key]];
          this.onSubmitOrder(params);
        } else {
          // 通过弹框修改
          this.$refs['form'].validate(valid => {
            if (valid) {
              if (this.settingsDialog.key === 'tel') {
                this.form.tel.value = JSON.stringify(this.form.tel.value);
              }
              const params = [this.form[this.settingsDialog.key]];
              this.onSubmitOrder(params);
            }
          });
        }
      },
      getCompanyList() {
        const params = {
          appListDomain: this.$storage.get('user').domain
        };
        this.$api.systemManage.getAppListdomain(params).then(res => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000' && data instanceof Array) {
            this.appList = data;
            this.formTop.appName = this.appList[0].name;
            this.getConfigList();
          }
        });
      }
    },
    created() {
      this.getCompanyList();
    },
    filters: {
      substrText(val, num) {
        if (val && val.length > num) {
          return val.substr(0, num) + '...';
        } else {
          return val;
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  .system-config {
    .line {
      text-align: center;
    }
    .tips-red {
      color: #f56c6c;
    }
    .likeFormItem {
      margin-bottom: 30px;
      label {
        display: inline-block;
        width: 80px;
        text-align: right;
        padding-right: 12px;
      }
    }
    .pdr_70 {
      padding-right: 70px;
    }
  }
</style>
<style lang="scss">
  [data-page='operation-app-setting'] {
    .table_list {
      table.gridtable {
        width: 100%;
        font-size: 14px;
        color: #606266;
        border-width: 1px;
        word-break:break-all;
        white-space:pre-wrap;
        text-align: center;
        tr {
          th {
          width: 25%;
          border-width: 1px;
          padding: 15px 10px;
          border-color: #303333;
          font-size: 14px;
          font-weight: bold;
          background-color: #f0f4f5;
          border-bottom: 1px solid #ebeef5;
        }
        td {
          width: 25%;
          border-width: 1px;
          padding: 15px 10px;
          border-color: #666666;
          background-color: #ffffff;
          border-bottom: 1px solid #ebeef5;
        }
            &:last-child {
                td {
                    border: none;
                }
            }
        }
      }
    }
  }
</style>
